package tech.kpretty.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Phone {
    private final Lock lock = new ReentrantLock();

    public synchronized void sendEmail() {
        System.out.println(Thread.currentThread().getName() + "--> 发送邮件...");
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void sendMSN() {
        // 尝试抢锁
        if (lock.tryLock()) {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "--> 发送信息...");
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        } else {
            System.out.println("超时...");
        }

    }
}

public class SynchronizedVsLock {
    public static void main(String[] args) {
        Phone phone = new Phone();
        new Thread(phone::sendMSN, "t1").start();
        new Thread(phone::sendMSN, "t2").start();
    }
}
